package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryBrandRelationDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.CategoryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationDao categoryBrandRelationDao;
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedisTemplate<String, String> redisTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @return
     */
    @Override
    public List<CategoryEntity> listCategoryTree() {
        //加单例锁
        synchronized (this) {
            //每个线程带锁进来之后都再去判断缓存中是否有数据
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            String s = valueOperations.get("CategoryEntitys");
            if (StringUtils.isEmpty(s)) {
                //查数据库
                System.out.println(Thread.currentThread().getName() + "缓存未命中---查数据库----");
                List<CategoryEntity> CategoryEntitys = getCategoryEntities();
                //缓存穿透解决，s1如果为null，CategoryEntitys缓存里的数据就是null
                String s1 = JSON.toJSONString(CategoryEntitys);
                //放缓存
                valueOperations.set("CategoryEntitys", s1, 1, TimeUnit.DAYS);
                return getCategoryEntities();
            } else {
                System.out.println(Thread.currentThread().getId() + "缓存已命中---取缓存----");
                return JSON.parseObject(s, new TypeReference<List<CategoryEntity>>() {
                });
            }
        }
    }


    public List<CategoryEntity> getCatalogJsonDbWithRedisLock() {
        String s = UUID.randomUUID().toString();
        //先去缓存中占锁
        //设置锁的过期时间是为了在删锁的时候出现了房屋宕机造成了死锁的情况
        //设置锁的随机value是为了
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", s, 500, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功，有资格去竞争请求数据库的权力
            List<CategoryEntity> categoryEntities = listCategoryTree();
            //拿到数据之后删锁
            if (redisTemplate.opsForValue().get("lock").equals(s)) {
                redisTemplate.delete("lock");
            }
            return categoryEntities;
        } else {
            //加锁失败
            //等待50ms
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //再去竞争占锁
            return getCatalogJsonDbWithRedisLock();
        }
    }

    /**
     * 一.Cacheable注解
     * 1.无需判断缓存里是否有，自动去判断
     * 2.不设置过期时间，默认永久保存，配置里改过期时间
     * 3.这边会将返回的数据进行java序列化，为了进行平台兼容。解决方法:进行json转换
     * 4.不设置key会默认给key
     * 5.线程穿透:在出现大并发的时候，springCache会加this锁，保证单例的运行
     * 6.线程击穿:加spring.cache.redis.cache-null-values注解
     *
     * @return
     */
    @Cacheable(value = "category", key = "#root.method.name")
    public List<CategoryEntity> getCategoryEntities() {
        //先查询商品的所有分类
        System.out.println("----getCategoryEntities----");
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        Integer count = categoryEntityList.size();
        //先查出一级商品分类
        return categoryEntityList.stream()
                .filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == 0;
                })
                .map(menu -> {
                    menu.setChildren(queryCategoryChildList(menu, categoryEntityList));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
    }

    /**
     * 批量删除商品分类
     *
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 考虑商品分类与其他关联的判断未处理

        baseMapper.deleteBatchIds(asList);
        //删缓存
        redisTemplate.delete("CategoryEntitys");
    }

    /**
     * 级联更新
     * 一、@CacheEvict 缓存失效
     * 1.在修改完数据库之后删除相应的数据缓存
     * 2.如果修改完之后要删除两个key值，使用Caching注解
     *
     * @param category
     */
//    @Caching(
//            evict = {
//                    @CacheEvict(cacheNames = "category", key = "'getCategoryEntities'"),
//                    @CacheEvict(cacheNames = "category", key = "'getCategoryEntities1'"),
//            }
//    )
    @CacheEvict(value = "category", allEntries = true)
    @Override
    public void updateDetail(CategoryEntity category) {
        //先更新自己
        this.updateById(category);
        //同步更新
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationDao.updateCategory(category.getCatId(), category.getName());
        }
        //删缓存
        redisTemplate.delete("CategoryEntitys");
//        System.out.println("修改数据库");
//        try {
//            System.out.println("执行修改业务");
////            Thread.sleep(10000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public List<CategoryEntity> listFirstCategory() {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_cid", 0);
        return this.list(wrapper);
    }

    /**
     * 缓存操作
     *
     * @return
     */
    @Override
    public Map<String, List<CategoryVo>> getCatalogJson() {
        //1.加入缓存(序列化和反序列化)
        String catalogJson = redisTemplate.opsForValue().get("catalogJsonFromDb");
        //假如1w的并发量都执行到这步判断。getCatalogJsonFromDb()里加锁
        if (StringUtils.isEmpty(catalogJson)) {
            Map<String, List<CategoryVo>> catalogJsonFromDb = getCatalogJsonFromDb();
            return catalogJsonFromDb;
        }

        //反序列化，将string转obj
        log.debug("取缓存");
        return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<CategoryVo>>>() {
        });
    }


    //从数据库中查询数据并封装
    private Map<String, List<CategoryVo>> getCatalogJsonFromDb() {

        //TODO 本地锁，如果在分布锁情况下锁不住
        //加单例锁
        synchronized (this) {

            //假如第一个人刚查完数据库出去还没返回结果，第二个人就进来了。这时候又会请求数据库。所以再加个判断
            String catalogJson = redisTemplate.opsForValue().get("catalogJsonFromDb");
            if (!StringUtils.isEmpty(catalogJson)) {
                //序列化,将obj转json
                return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<CategoryVo>>>() {
                });
            }

            //先查出所有的数据
            List<CategoryEntity> list = this.baseMapper.selectList(null);

            //先查一级分类的数据
            Map<String, List<CategoryVo>> map = getParentCid(list, 0L).stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                //查询出二级分类的数据
                List<CategoryEntity> categoryEntities = getParentCid(list, v.getCatId());
                List<CategoryVo> categoryVos = null;
                if (!CollectionUtils.isEmpty(categoryEntities)) {
                    categoryVos = categoryEntities.stream().map(c -> {
                        //封装数据
                        CategoryVo categoryVo = new CategoryVo();
                        categoryVo.setCatalog1Id(v.getCatId());
                        categoryVo.setId(c.getCatId());
                        categoryVo.setName(c.getName());
                        //三级分类
                        //查询出三级分类的数据
                        List<CategoryEntity> category3Entities = getParentCid(list, c.getCatId());
                        List<CategoryVo.CategoryVo2> c3List = null;
                        if (category3Entities != null && category3Entities.size() > 0) {
                            c3List = category3Entities.stream().map(c3 -> {
                                CategoryVo.CategoryVo2 categoryVo3 = new CategoryVo.CategoryVo2();
                                categoryVo3.setCatalog2Id(c.getCatId());
                                categoryVo3.setId(c3.getCatId());
                                categoryVo3.setName(c3.getName());
                                return categoryVo3;
                            }).collect(Collectors.toList());
                        }
                        categoryVo.setCatalog3List(c3List);

                        return categoryVo;
                    }).collect(Collectors.toList());
                }
                return categoryVos;
            }));
            //放入缓存
            redisTemplate.opsForValue().set("catalogJsonFromDb", JSON.toJSONString(map));
            return map;
        }
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> categoryEntities, Long parentId) {
        return categoryEntities.stream().filter(item -> {
            return item.getParentCid() == parentId;
        }).collect(Collectors.toList());
    }

    /**
     * 找到该菜单在所有菜单里的儿子
     *
     * @param root               父亲
     * @param categoryEntityList
     * @return
     */
    List<CategoryEntity> queryCategoryChildList(CategoryEntity root, List<CategoryEntity> categoryEntityList) {
        return categoryEntityList.stream()
                .filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == root.getCatId();
                })
                .map(menu -> {
                    menu.setChildren(queryCategoryChildList(menu, categoryEntityList));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
    }

    //先设置当前的菜单id，然后判单如果没父亲，就返回，如果有父亲就进递归。
    List<Long> findCategoryPath(Long catelogId, List<Long> resultList) {
        CategoryEntity categoryEntity = this.getById(catelogId);
        //添加当前节点的路径
        resultList.add(0, categoryEntity.getCatId());
        //如果有父节点
        if (!(categoryEntity.getParentCid() == 0 || categoryEntity.getParentCid() == null)) {
            //进入父节点添加父节点路径
            findCategoryPath(categoryEntity.getParentCid(), resultList);
        }
        return resultList;
    }
}